from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm.session import Session

from airflow.models.base import Base
from airflow.models.idata_auth_role_resource import AuthRoleResource
from airflow.utils import dates
from airflow.utils.session import provide_session


class AuthResource(Base):
    """the class to get user info."""

    __tablename__ = "idata_auth_resource"
    __table_args__ = {"useexisting": True}

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32))
    url_prefix = Column(String(255))
    create_time = Column(DateTime)
    enable = Column(Integer)

    def __init__(self,name,url_prefix,create_time):
        self.name = name
        self.url_prefix = url_prefix
        self.create_time = create_time
        self.enable = 0

    @staticmethod  # 静态方法
    @provide_session
    def get_resource(id, rid, session: Session = None):
        q = session.query(AuthResource).outerjoin(AuthRoleResource, AuthRoleResource.resource_id == AuthResource.id)
        if id:
            q = q.filter(AuthResource.id == id)
        if rid:
            q = q.filter(AuthRoleResource.role_id == rid)
        return q.all()

    @staticmethod  # 静态方法
    @provide_session
    def get_resources(session: Session = None):
        return session.query(AuthResource).all()

    @staticmethod
    @provide_session
    def get_resources_page(page, session: Session = None):
        return session.query(AuthResource).order_by(AuthResource.create_time).paginate(page, 10, error_out=False)

    @staticmethod
    @provide_session
    def add_resources(resource, session: Session = None):
        return session.add(resource)

    @staticmethod
    @provide_session
    def delete_resource(id, session: Session = None):
        session.query(AuthResource).filter(AuthResource.id == id).delete()

    @staticmethod
    @provide_session
    def update_resource(resource , session: Session = None):
        result = session.query(AuthResource).filter(AuthResource.id == resource.id).first()
        if result is None:
            return
        else:
            return session.merge(resource)

    def to_json(self):
        """
        Get the User in a json structure

        :return: the User object in json format
        """
        if self is None:
            return None
        data = {
            'id': self.id,
            'name': self.name,
            'url_prefix': self.url_prefix,
            'create_time': dates.to_milliseconds(self.create_time),
            'enable': self.enable
        }
        return data






